<?php


namespace app\index\controller;


use app\model\Member;
use app\model\Order;
use app\model\OrderStaff;
use app\model\Technical;
use app\model\TechnicalBail;

class TechnicalbailController extends Base
{
    public function getBail(){
        $uid = UID();
        $technical = Technical::where(['uid'=>$uid])->find();
        if(empty($technical)){
            return $this->json(['data'=>['bail'=>0.00]]);
        }else{
            $technical = $technical->toArray();
        }
        return $this->json(['data'=>['bail'=>$technical['bail']]]);
    }

    public function recharge(){
        $uid = UID();
        $technical = Technical::where(['uid'=>$uid])->find();
        if(empty($technical)){
            return $this->json(['errno'=>1,'msg'=>'充值失败']);
        }else{
            $technical = $technical->toArray();
        }

        $bail = TechnicalBail::create([
            'type'=>1,
            'amount'=>input('post.amount'),
            'uuid'=> $technical['uuid']
        ]);
        $bail->toArray();

        return $this->json(['data'=>$bail]);
    }

    public function withdraw(){
        $amount = input('post.amount');

        $uid = UID();

        $technical = Technical::where(['uid'=>$uid])->find();
        if(empty($technical)){
            return $this->json(['errno'=>1,'msg'=>'提现失败']);
        }else{
            $technical = $technical->toArray();
        }

        $orderStaff = OrderStaff::where(['uuie'=>$technical['uuid']])->select()->toArray();
        $orders = Order::whereIn('id',array_column($orderStaff,'order_id'))->where('order_status_id','<',5)->select()->toArray();

        if(count($orders)){
            return $this->json(['errno'=>1,'msg'=>'提现失败：有服务订单未完成']);
        }

        if($technical['bail'] < $amount) {
            return $this->json(['errno'=>1,'msg'=>'提现失败：保证金余额不足']);
        }

        if(TechnicalBail::addBail([
            'type'=>1,
            'amount'=>$amount,
            'uuid'=>  $technical['uuid']
        ])){
            return $this->json(['errno'=>1,'msg'=>'提现失败']);
        }

        return $this->json([]);
    }

    public function bailLog(){
        $uid = UID();
        $technical = Technical::where(['uid'=>$uid])->find();
        if(empty($technical)){
            return $this->json(['data'=>[]]);
        }else{
            $technical = $technical->toArray();
        }


        $res = TechnicalBail::where(['uuid'=>$technical['uuid']])->select()->toArray();


        return $this->json(['data'=>$res]);
    }
}
